/**
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 */

import './lineHeight.css';

import {$getSelection, LexicalEditor} from 'lexical';
import * as React from 'react';
import {useCallback} from 'react';

import {$patchStyleText} from '@lexical/selection';

import DropDown, {DropDownItem} from '../../ui/DropDown';

export function parseLineHeightForToolbar(input: string): string {
  // 如果没有输入或者是数字，直接返回
  if (!input || /^\d+(\.\d+)?$/.test(input)) {
    return input || '1.7';
  }
  
  // 如果是像素值，转换为数字
  const pxMatch = input.match(/^(\d+(?:\.\d+)?)px$/);
  if (pxMatch) {
    // 这里可以根据需要进行转换，暂时返回原值
    return input;
  }
  
  return input;
}

const LINE_HEIGHT_OPTIONS: [string, string][] = [
  ['1', '1'],
  ['1.15', '1.15'],
  ['1.5', '1.5'],
  ['1.7', '默认行高'],
  ['2', '2'],
  ['2.5', '2.5'],
  ['3', '3'],
];

function dropDownActiveClass(active: boolean) {
  if (active) {
    return 'active dropdown-item-active';
  } else {
    return '';
  }
}

export default function LineHeight({
  selectionLineHeight,
  disabled,
  editor,
}: {
  selectionLineHeight: string;
  disabled: boolean;
  editor: LexicalEditor;
}) {
  const handleClick = useCallback(
    (option: string) => {
      editor.update(() => {
        const selection = $getSelection();
        if (selection !== null) {
          $patchStyleText(selection, {
            'line-height': option,
          });
        }
      });
    },
    [editor],
  );

  // 获取当前行高值，默认为 1.7
  const currentLineHeight = selectionLineHeight || '1.7';
  
  // 根据行高值显示对应的标签
  const getDisplayLabel = (lineHeight: string) => {
    return lineHeight === '1.7' ? '默认行高' : lineHeight;
  };

  return (
    <DropDown
      disabled={disabled}
      buttonClassName="toolbar-item line-height"
      buttonLabel={getDisplayLabel(currentLineHeight)}
      buttonAriaLabel="Formatting options for line height">
      {LINE_HEIGHT_OPTIONS.map(([option, text]) => (
        <DropDownItem
          className={`item ${dropDownActiveClass(currentLineHeight === option)} lineheight-item`}
          onClick={() => handleClick(option)}
          key={option}>
          <span className="text">{text}</span>
        </DropDownItem>
      ))}
    </DropDown>
  );
}